package com.gan.yidademo.leave.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gan.yidademo.dormitory.mapper.StayOutLateMapper;
import com.gan.yidademo.leave.mapper.StuLeaveMapper;
import com.google.common.collect.Maps;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.aliyun.dingtalkyida_1_0.models.SearchFormDatasHeaders;
import com.aliyun.dingtalkyida_1_0.models.SearchFormDatasRequest;
import com.aliyun.dingtalkyida_1_0.models.SearchFormDatasResponse;
import com.aliyun.dingtalkyida_1_0.models.SearchFormDatasResponseBody;
import com.aliyun.tea.TeaException;
import com.aliyun.teautil.models.RuntimeOptions;
import com.gan.yidademo.common.exception.BusinessException;
import com.gan.yidademo.common.util.YiDaUtil;
import com.gan.yidademo.dormitory.model.StayOutLate;
import com.gan.yidademo.leave.model.StuLeave;
import com.gan.yidademo.leave.service.StuLeaveService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author gbw
 * @date 2023/9/22
 */
@Slf4j
@Service
public class StuLeaveServiceImpl extends ServiceImpl<StuLeaveMapper, StuLeave> implements StuLeaveService {

    @Value("${DingDing.ak}")
    private String ak;
    @Value("${DingDing.sk}")
    private String sk;
    /**
     * 应用编码
     */
    @Value("${YiDa.stu_leave.appType}")
    private String appType;
    /**
     * 应用秘钥
     */
    @Value("${YiDa.stu_leave.systemToken}")
    private String systemToken;
    /**
     * 用户Id
     */
    @Value("${DingDing.userId}")
    private String userId;
    /**
     * 表单ID
     */
    @Value("${YiDa.stu_leave.formUuid}")
    private String formUuid;


    @Override
    public Map<String, Object> getFormData() {
        String token;
        try {
            token = YiDaUtil.getTokenFromApp(ak, sk);
        } catch (Exception e) {
            throw new BusinessException("获取token失败" + e.getMessage());
        }


        com.aliyun.dingtalkyida_1_0.Client client;
        try {
            client = YiDaUtil.createClient();
        } catch (Exception e) {
            throw new BusinessException("创建宜搭客户端失败!");
        }
        SearchFormDatasHeaders searchFormDatasHeaders = new SearchFormDatasHeaders();
        searchFormDatasHeaders.xAcsDingtalkAccessToken = token;
        SearchFormDatasRequest searchFormDatasRequest = new SearchFormDatasRequest()
                .setAppType(appType)
                .setSystemToken(systemToken)
                .setUserId(userId)
                .setFormUuid(formUuid)
                .setCurrentPage(1)
                .setPageSize(10);
        try {
            SearchFormDatasResponse stuLeaveResp = client.searchFormDatasWithOptions(searchFormDatasRequest, searchFormDatasHeaders, new RuntimeOptions());
            SearchFormDatasResponseBody body = stuLeaveResp.getBody();
            List<SearchFormDatasResponseBody.SearchFormDatasResponseBodyData> data = body.getData();
            List<StuLeave> stuLeaveList = new ArrayList<>();
            for (SearchFormDatasResponseBody.SearchFormDatasResponseBodyData stu : data) {
                StuLeave stuLeave = new StuLeave();
                String instanceValue = stu.getInstanceValue();
                JSONArray jsonArray = new JSONArray(instanceValue);
                jsonArray.forEach(obj -> {
                    JSONObject jsonObject = (JSONObject) obj;
                    String fieldId = (String) jsonObject.get("fieldId");
                    // 设置字段信息
                    switch (fieldId) {
                        case "dateField_l8jsyhku":
                            JSONObject beginTimeData = (JSONObject) jsonObject.get("fieldData");
                            Date beginTime = new Date((Long) beginTimeData.get("value"));
                            stuLeave.setBeginTime(beginTime);
                            break;
                        case "dateField_l8jsyhkv":
                            JSONObject endTimeData = (JSONObject) jsonObject.get("fieldData");
                            Date endTime = new Date((Long) endTimeData.get("value"));
                            stuLeave.setEndTime(endTime);
                            break;
                        case "ccStudentField_ln00srhz":
                            JSONObject stuNameData = (JSONObject) jsonObject.get("fieldData");
                            JSONArray stuArray = (JSONArray) stuNameData.get("value");
                            JSONObject stuInfo = (JSONObject) stuArray.get(0);
                            String stuName = (String) stuInfo.get("text");
                            stuLeave.setStuName(stuName);
                            break;
                        case "employeeField_l8jsyhkr":
                            JSONObject patriarchData = (JSONObject) jsonObject.get("fieldData");
                            JSONArray patriarchArray = (JSONArray) patriarchData.get("value");
                            JSONObject patriarchInfo = (JSONObject) patriarchArray.get(0);
                            String patriarchId = (String) patriarchInfo.get("key");// 提交者的id
                            String patriarchName = (String) patriarchInfo.get("label");// 提交者的姓名
                            stuLeave.setPatriarchName(patriarchName);
                            stuLeave.setPatriarchId(patriarchId);
                            break;
                        case "employeeField_ln00sri3":
                            JSONObject headTeacherData = (JSONObject) jsonObject.get("fieldData");
                            JSONArray headTeacherArray = (JSONArray) headTeacherData.get("value");
                            JSONObject teaInfo = (JSONObject) headTeacherArray.get(0);
                            String headTeacher = (String) teaInfo.get("label");
                            stuLeave.setHeadTeacher(headTeacher);
                            break;
                    }
                });
                stuLeaveList.add(stuLeave);
            }
            this.saveBatch(stuLeaveList);
            return null;
        } catch (Exception _err) {
            TeaException err = new TeaException(_err.getMessage(), _err);
            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                // err 中含有 code 和 message 属性，可帮助开发定位问题
                log.error("宜搭获取学生请假信息报错 ====== code={}，message={}", err.code, err.message);
            }
            throw new BusinessException(err.getMessage());
        }
    }
}
